import axios from 'axios'
import qs from 'qs'
import router from "../../router/router";
import Utils from "../../js/Utils";

export default {
	namespaced: true,
	actions: {
		login: function (context, params) {
			let {info, posted, valid, formLogin} = params;
			//======处理表单错误==============================================
			if (!valid) {
				info("error", '表单数据有误');
				return;
			}
			//======处理频繁请求==============================================
			if (posted.login) {
				info("warning", "请求过于频繁");
				return;
			}
			posted.login = true;
			setTimeout(() => posted.login = false, 3000);
			//=======处理Data=============================================
			params.onget = data => {
				let {success, user} = data;
				
				if (success) {
					Utils.setItem("logininfo", {
						id: user.id,
						login: true,
						admin: false
					});
					info("success", "登录成功");
					context.dispatch("init");
					router.push("/");
				} else {
					posted.login = false;
					formLogin.password = "";
					info("error", "登录失败，用户名或密码错误");
				}
			};
			//////////////////////////////////////////////////////
			context.commit("login", params)
		},
		register: function (context, params) {
			let {callback, info, posted, valid} = params;
			params.onget = data => {
				let {success, user} = data
				if (!valid) {
					info("error", "表单填写有误")
					return
				}
				if (success) {
					Utils.setItem("registerinfo", {
						register: true,
						admin: false
					});
					callback(user);
					info("success", "注册成功");
					router.push("/login");
				} else {
					posted.register = false;
					info("error", "注册失败，用户已存在");
				}
			}
			context.commit("register", params)
		},
		getUser: function (context, params) {
			let {callback, info} = params;
			params.onget = data => {
				let {success, user} = data
				if (success) {
					callback(user)
				}
			}
			context.commit("getUser", params);
		},
		init: function ({commit}, params) {
			commit("init", {
				onget: ({user}) => {
					params && params.callback && params.callback(user);
					commit("register", ["user", user || {}], {root: true});
				}
			})
		},
	},
	mutations: {
		login: function (state, {username, password, onget}) {
			axios.post('/login', qs.stringify({
				username,
				password
			})).then(({data}) => {
				onget(data);
			});
		},
		register: function (state, {username, password, email, tel, onget}) {
			axios.post('/user/register',
				{
					username, password, email, tel
				})
				.then(({data}) => {
					onget(data)
				})
		},
		getUser: function (state, {id, onget}) {
			axios.get('/user/' + id).then(({data}) => {
				onget(data)
			})
		},
		init: function (state, {onget}) {
			axios.get("/user/login").then(({data}) => {
				onget(data);
			})
		},
	}
	
}